﻿package javase.io;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;


/**
 * 在xml文件中添加新节点
 * */
public class DomXmlWriter {
	public static void main(String[] args) {
		
		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc = db.parse(new File("src/com/javase/xml/demo/FirstXml.xml"));
			Element ebody = doc.createElement("body");
			
			/** 创建hr的属性并赋值*/
			Element ehr = doc.createElement("hr");
			Attr acolor = doc.createAttribute("color");
			ehr.setAttributeNode(acolor);
			acolor.setNodeValue("red");
			ebody.appendChild(ehr);
			
			/** 创建text属性并赋值*/
			Element etext = doc.createElement("text");
			Text testmsg = doc.createTextNode("create dom");
			etext.appendChild(testmsg);
			ebody.appendChild(etext);
			
			doc.getDocumentElement().appendChild(ebody);
			TransformerFactory tff = TransformerFactory.newInstance();
			Transformer tf = tff.newTransformer();
			DOMSource doms = new DOMSource(doc);
			StreamResult sr = new StreamResult(new File("src/com/javase/xml/demo/SecondXml.xml"));
			tf.transform(doms, sr);
			
			
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		} catch (TransformerException e) {
			e.printStackTrace();
		}
		
	}
}
